<template>
  <div class="customer-container">
    <GroupList />
    <ChatSidebar />
    <ChatMain />
    <ChatInfo />
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, computed, nextTick } from 'vue';
import ChatSidebar from '../components/ChatSidebar.vue';
import ChatMain from '../components/ChatMain.vue';
import ChatInfo from '../components/ChatInfo.vue';
import GroupList from '../components/GroupList.vue';
import { WebSocketService } from '../utils/websocket';
import moment from 'moment';
import { useChatStore } from '../stores/chat';
defineOptions({
  name: 'CustomerPage'
});
// 使用Pinia Store
const chatStore = useChatStore();
const messageList = computed(() => chatStore.messageList);
const selectedContact = computed(() => chatStore.selectedContact);
const chatMessages = computed(() => chatStore.chatMessages);
// 创建WebSocket实例
const accessToken = localStorage.getItem('accessToken')?.replace('Bearer ', '') || '';
const wsUrl = `ws://8.210.209.47:25010/api?JwtToken=${accessToken}`;
const ws = new WebSocketService(wsUrl);

// 处理接收到的WebSocket消息
const handleWebSocketMessage = (message) => {
  if (message.type === 'MSGNEW') {
    const data = message.data;
    // 检查消息是否属于当前联系人列表中的某个联系人
    const matchedContact = messageList.value.find(contact => 
      contact.contactId === (data.Dr === 1 ? data.From : data.To)
    );
    if (matchedContact) {
      // 格式化消息数据并确保大小写匹配
      const formattedMessage = {
        MsgId: data.MsgId,
        From: data.From,
        To: data.To,
        MsgType: data.MsgType,
        Dr: data.Dr,
        Ts: data.Ts,
        Payload: {
          Text: data.Payload?.text || data.Payload?.Text || '',
          TrText: data.Payload?.trText || data.Payload?.TrText || '',
          Media: data.Payload?.media || data.Payload?.Media || [],
          Contacts: data.Payload?.contacts || data.Payload?.Contacts || [],
          Contactsname: data.Payload?.contactsname || data.Payload?.Contactsname || '',
          LinkBody: data.Payload?.linkBody || data.Payload?.LinkBody || null
        },
        Packedid: data.Packedid || data.packedId
      };
      // 使用store的action来更新消息
      chatStore.receiveMessage(formattedMessage);
      // 如果是当前选中的联系人，强制触发视图更新并滚动到底部
      if (selectedContact.value && 
          (formattedMessage.From === selectedContact.value.contactId || 
           formattedMessage.To === selectedContact.value.contactId)) {
        nextTick(() => {
          chatStore.scrollToBottom();
        });
      }
    }
  }
};
// 在组件挂载时连接WebSocket并注册消息处理器
onMounted(() => {
  // 连接WebSocket
  ws.connect();
  // 添加消息处理器
  ws.addMessageHandler(handleWebSocketMessage);
  // 获取联系人详情
  chatStore.fetchContactsList();
  // 获取聊天列表
  chatStore.fetchChatsList().then(() => {
    // 如果有聊天列表，选择第一个联系人
    if (messageList.value.length > 0) {
      chatStore.fetchChatMessages(messageList.value[0]);
      chatStore.scrollToBottom();
    }
  });
});
// 在组件卸载时断开WebSocket连接
onUnmounted(() => {
  ws.removeMessageHandler(handleWebSocketMessage);
  ws.disconnect();
});
</script>

<style scoped>
.customer-container {
  background-color: #f1f3f6;
  padding: 20px;
  display: flex;
  height: 100vh;
  overflow: hidden;
  box-sizing: border-box;
  gap: 12px;
}
</style>